package com.ruoyi.framework.aspectj;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.system.domain.SysOperAudit;
import com.ruoyi.system.service.ISysOperAuditService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

@Aspect
@Component
public class OperAuditAspect {
    private static final Logger log = LoggerFactory.getLogger(OperAuditAspect.class);

    @Autowired
    private ISysOperAuditService operAuditService;

    @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) {
        handleLog(joinPoint, controllerLog, null, jsonResult);
    }

    @AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e) {
        handleLog(joinPoint, controllerLog, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult) {
        try {
            // 获取当前请求对象
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes == null) {
                return;
            }

            // 获取当前用户（简化版）
            String username = "anonymous";
            try {
                username = ServletUtils.getRequest().getRemoteUser();
                if (username == null) {
                    username = "anonymous";
                }
            } catch (Exception ex) {
                log.warn("获取用户信息失败: {}", ex.getMessage());
            }

            // 封装审计日志
            SysOperAudit operAudit = new SysOperAudit();
            operAudit.setTitle(controllerLog.title());
            operAudit.setBusinessType(controllerLog.businessType().name());
            operAudit.setMethod(joinPoint.getSignature().getName());
            operAudit.setOperName(username);
            operAudit.setOperUrl(attributes.getRequest().getRequestURI());
            operAudit.setOperIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
            operAudit.setOperTime((java.sql.Date) new Date());

            // 保存审计日志
            operAuditService.insertOperAudit(operAudit);
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("保存操作审计日志异常:{}", exp.getMessage());
        }
    }
}